package com.zxkj.commonpatrol.ui;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.czy.basecommon.utils.base.BaseVmDataBindingActivity;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xui.widget.toast.XToast;
import com.zxkj.commonpatrol.BR;
import com.zxkj.commonpatrol.R;
import com.zxkj.commonpatrol.adapt.MyTextSimpleAdapter;
import com.zxkj.commonpatrol.databinding.ActivityExceptionDetailBinding;
import com.zxkj.commonpatrol.model.entity.Group;
import com.zxkj.commonpatrol.model.entity.GruopBean;
import com.zxkj.commonpatrol.viewmodel.ExceptionDetailViewModel;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

public class ExceptionDetailActivity extends BaseVmDataBindingActivity<ActivityExceptionDetailBinding, ExceptionDetailViewModel>implements
        GoogleMap.OnMyLocationButtonClickListener,
        GoogleMap.OnMyLocationClickListener,
        OnMapReadyCallback {

    private FusedLocationProviderClient mFusedLocationProviderClient;
    private GoogleMap mMap;
    private MiniLoadingDialog miniLoadingDialog;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_exception_detail;
    }

    @Override
    public int initVariableId() {
        return BR.mExceptionDetailViewModel;
    }


    @Override
    protected void initUI() {
        miniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this);
//        miniLoadingDialog.show();
        SupportMapFragment mapFragment =
                (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this);
        binding.recy1.setLayoutManager(linearLayoutManager);

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void dataObserver() {
        super.dataObserver();

        LiveEventBus.get("cs", Group.class).observeSticky(this, new Observer<Group>() {
            @Override
            public void onChanged(Group s) {
                List<Group> groups = new ArrayList<>();
                groups.add(s);
                MyTextSimpleAdapter adapter =new MyTextSimpleAdapter(binding.recy1,groups,ExceptionDetailActivity.this);
                binding.recy1.setAdapter(adapter);

            }
        });

    }

    @Override
    public boolean onMyLocationButtonClick() {
        return false;
    }

    @Override
    public void onMyLocationClick(@NonNull Location location) {

    }

    @Override
    public void onMapReady(GoogleMap map) {
        mMap = map;

        mMap.setOnMyLocationButtonClickListener(this);
        mMap.setOnMyLocationClickListener(this);



        enableMyLocation();
    }

    private void enableMyLocation() {
        if (mMap != null) {
            mMap.setMyLocationEnabled(true);
            updateLocationUI();
            getDeviceLocation();
        }
    }

    private void getDeviceLocation() {
        try {


            Task locationResult = mFusedLocationProviderClient.getLastLocation();
            locationResult.addOnCompleteListener(this, new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if (task.isSuccessful()) {
                        // Set the map's camera position to the current location of the device.

//                        miniLoadingDialog.dismiss();
                        Location mLastKnownLocation = (Location) task.getResult();
                        if (mLastKnownLocation==null){
                            return;
                        }
                        double latitude = mLastKnownLocation.getLatitude();
                        double longitude = mLastKnownLocation.getLongitude();


                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(
                                new LatLng(latitude,
                                        longitude), 18));



                        Geocoder geocoder = new Geocoder(ExceptionDetailActivity.this, Locale.getDefault());
                        List<Address> addresses = null;
                        try {
                            addresses = geocoder.getFromLocation(latitude, longitude, 1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        if (addresses != null&& addresses.size() > 0) {
                            String locality = addresses.get(0).getLocality() + addresses.get(0).getFeatureName();
                            binding.tvAddress.setText(locality);

                        } else {
                            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(null, 18));
                            mMap.getUiSettings().setMyLocationButtonEnabled(false);
                        }


                    } else {
//                        miniLoadingDialog.dismiss();
                        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(null, 18));
                        mMap.getUiSettings().setMyLocationButtonEnabled(false);
                    }
                }
            });

        } catch(SecurityException e)  {
            miniLoadingDialog.dismiss();
            Log.e("Exception: %s", e.getMessage());
        }
    }

    private void updateLocationUI() {
        if (mMap == null) {
            return;
        }

        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.setMinZoomPreference(18);
    }
}
